package com.fanshuai.spring.boot.config;

import com.alibaba.druid.pool.xa.DruidXADataSource;
import com.mysql.cj.jdbc.MysqlXADataSource;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.XADataSource;

@Configuration
@Data
public class XADataSourceConfig {
    @Value("${db.test.url}")
    private String urlTest;

    @Value("${db.test.user}")
    private String usernameTest;

    @Value("${db.test.password}")
    private String passwordTest;

    @Value("${db.test2.url}")
    private String urlTest2;

    @Value("${db.test2.user}")
    private String usernameTest2;

    @Value("${db.test2.password}")
    private String passwordTest2;

    @Value("${druid.xa.enabled:false}")
    private boolean druidXAEnabled;

    private XADataSource getXADataSource(String url, String username, String password) {
        if (druidXAEnabled) {
            DruidXADataSource xaDataSource = new DruidXADataSource();
            xaDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
            xaDataSource.setUrl(url);
            xaDataSource.setUsername(username);
            xaDataSource.setPassword(password);

            xaDataSource.setMaxActive(100);
            xaDataSource.setMaxWait(1000);
            xaDataSource.setMinIdle(5);
            xaDataSource.setTimeBetweenEvictionRunsMillis(1000);

            xaDataSource.setTestOnBorrow(true);
            xaDataSource.setTestOnReturn(true);
            xaDataSource.setTestWhileIdle(true);

            return xaDataSource;
        } else {
            MysqlXADataSource dataSource = new MysqlXADataSource();
            dataSource.setURL(url);
            dataSource.setUser(username);
            dataSource.setPassword(password);

            return dataSource;
        }
    }

    @Bean(name = "xaDataSource1")
    public XADataSource xaDataSource1() {
        return getXADataSource(urlTest, usernameTest, passwordTest);
    }

    @Bean(name = "xaDataSource2")
    public XADataSource xaDataSource2() {
        return getXADataSource(urlTest2, usernameTest2, passwordTest2);
    }
}
